// manager/pages/areadesc/index.js
import config from '../../../utils/config';
import { getSystemInfo } from '../../../utils/getSystemInfo';
import { request } from '../../../utils/request';
import util from '../../../common/util';
import WxValidate from '../../../common/WxValidate';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        perAreaId: "",
        merchantType: "",
        params: {
            search: "",
            phone: "",
            // industry: "",
        },
        // 行业字典
        // industryList: [],
        // industryIndex: -1,
        scroller: {
			pageNum: 0,
			pageSize: 10,
			totalPage: 10,
			isNoneLoading: true,
			refreshColor: '#000000',
			refreshDiy: false,
			isloaded: false,
			list: []
        },
        isDeleteProcess: "",
        isDelete: "",
        show: false,
        actions: [],
        phone: "",
        // 转交
        depList: [],
        custList: [],
        showTransfer: false,
        transferForm: {
            perCustName: "",
            merchantId: "",
            // 1-个人，2-商户，3-企业，4-新型农业主体
            merchantType: "",
            recipientDeptId: "",
            recipientId: ""
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if(options.name){
            wx.setNavigationBarTitle({
                title: options.name
            })
        }
        this.setData({
            perAreaId: options.id,
            merchantType: options.merchantType,
        })
        // this.getDictionaryInfo();
        this.getSameLevelDepts();
        this.getSysConfigInfo1();
        this.getSysConfigInfo2();
        this.initValidate();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.resetScroller()
        this.getMyPersonList();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 获取我的个人
     */
    getMyPersonList() {
		let { scroller } = this.data;
        scroller.pageNum = scroller.pageNum + 1;
        if(scroller.pageNum>scroller.totalPage){
            return
        }
        request({
            url: `/personMarketing/getMyPersonList`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                ...this.data.params,
                perAreaId: this.data.perAreaId,
                pageNum: this.data.scroller.pageNum,
                pageSize: this.data.scroller.pageSize,
            }
        }).then(res => {
            if(res.code == 0){
                console.log(res)
                scroller.totalPage = Math.ceil(res.total/scroller.pageSize);
                if(scroller.pageNum>=scroller.totalPage){
                    scroller.isNoneLoading = false;
                }
                if(res.data.length>0){
                    res.data.map(item => {
                        item.creationTime = util.formatTime(new Date(item.creationTime));
                        item.lastVisitDate = item.lastVisitDate?util.formatTime(new Date(item.lastVisitDate)):"";
                        return item
                    })
                }
                if(scroller.pageNum == 1){
                    scroller.list = res.data;
                }else{
                    scroller.list = scroller.list.concat(res.data);
                }
                this.setData({
                    scroller
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    /**
     * 获取字典
     */
    // getDictionaryInfo() {
    //     request({
    //         url: "/commonApi/getDictionaryInfo",
    //         method: "GET",
    //         data: {
    //             dictType: 'ecard_enterprise_industry'
    //         }
    //     }).then(res => {
    //         if(res.code == 0){
    //             let industryList = [];
    //             industryList.push({
    //                 dictLabel: "全部",
    //                 dictValue: ""
    //             })
    //             this.setData({
    //                 industryList: industryList.concat(res.data)
    //             })
    //         }
    //     }).catch(error => {
    //         // console.log(error)
    //     })
    // },
    /**
     * 输入框输入时
     */
    input(e){
        let key = e.target.dataset.key;
        this.setData({
            ['params.'+key]: e.detail.value,
            // isFilter: !!e.detail.value,
        })
    },
    bindPickerChange(e){
        this.setData({
            industryIndex: e.detail.value,
            'params.industry': this.data.industryList[e.detail.value].dictValue
        })
    },
    // 搜索
    searchConfirm(e){
        console.log(e)
        let key = e.currentTarget.dataset.key;
        this.setData({
            ['params.'+key]: e.detail.value,
        })
        // 页面加载时执行一次加载
		this.resetScroller()
        this.getMyPersonList();
    },
    searchBtn(e){
        this.resetScroller()
        this.getMyPersonList();
    },

    /**
     * 重置下拉
     */
    resetScroller(){
        let scroller = {
			pageNum: 0,
			pageSize: 10,
			totalPage: 10,
			isNoneLoading: true,
			refreshColor: '#000000',
			refreshDiy: false,
			isloaded: false,
			list: []
		}
		this.setData({
            scroller,
		})
    },

    refresh: function () {
        this.resetScroller()
        this.getMyPersonList()
    },
    
	loadMore: function () {
        console.log("loadMore")
		this.getMyPersonList()
    },

    /**
     * 拨打电话
     */
    makePhoneCall(e) {
        console.log(e)
        let { phone } = e.currentTarget.dataset;
        if(!phone){
            wx.showToast({
                title: "暂无联系方式",
                icon: 'none',
                duration: 2000
            })
            return
        }
        getSystemInfo({
            android: () => {
                let actions = [
                    { name: phone, color: '#999', disabled: true },
                    { name: '呼叫', color: '#000' },
                ]
                this.setData({
                    show: true,
                    phone: phone,
                    actions
                })
            },
            ios: () => {
                wx.makePhoneCall({
                    phoneNumber: phone
                })
            }
        })
    },
    onSelect(e) {
        console.log(e)
        this.setData({
            show: false
        })
        wx.makePhoneCall({
            phoneNumber: this.data.phone
        })
    },
    onCancel() {
        this.setData({ show: false });
    },

    /** 导航 */
    navigateTo(e) {
        // console.log(e.currentTarget.dataset)
        let { coordinate, name } = e.currentTarget.dataset;
        if(!coordinate){
            wx.showToast({
                title: "暂无位置信息",
                icon: 'none',
                duration: 2000
            })
            return
        }
        let arr = coordinate.split(",")
        wx.openLocation({
            name,
            latitude: Number(arr[0]),
            longitude: Number(arr[1])
        })
    },

    /**
     * 获取同级部门列表
     */
    getSameLevelDepts() {
        request({
            url: `/dept/getSameLevelDepts`,
            method: "GET"
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    depList: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    /**
     * 根据机构ID获取客户经理
     */
    getUserListByDeptId(deptId) {
        request({
            url: `/user/getUserListByDeptId`,
            method: "GET",
            reqRSAENCRY: false, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                deptId
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    custList: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    /**
     * 获取删除权限
     */
    getSysConfigInfo1() {
        request({
            url: "/commonApi/getSysConfigInfo",
            method: "GET",
            data: {
                configKey: "ecard_merchant_isdelete"
            }
        }).then(res => {
            console.log(res)
            if(res.code == 0){
                this.setData({
                    isDelete: Number(res.data.configValue),
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    /**
     * 获取删除流程权限
     */
    getSysConfigInfo2() {
        request({
            url: "/commonApi/getSysConfigInfo",
            method: "GET",
            data: {
                configKey: "ecard_del_flow_sts"
            }
        }).then(res => {
            console.log(res)
            if(res.code == 0){
                // 1启用，2停用
                this.setData({
                    isDeleteProcess: Number(res.data.configValue),
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    /**
     * 选择框变化时
     */
    pickerChagne(e){
        let { key, value } = e.detail;
        if(key == "recipientDeptId"){
            if(value == this.data.transferForm.recipientDeptId){
               return 
            }
            this.getUserListByDeptId(value)
            this.setData({
                ['transferForm.'+key]: value,
                "transferForm.recipientId": ""
            })
        }else{
            this.setData({
                ['transferForm.'+key]: value
            })
        }
        
    },
    /** 转交弹窗 */
    transferMerchant(e){
        let { item } = e.currentTarget.dataset;
        let { transferForm, merchantType } = this.data;
        Object.keys(transferForm).forEach(key => transferForm[key] = "")
        transferForm.perCustName = item.perCustName;
        transferForm.merchantId = item.id;
        transferForm.merchantType = merchantType;
        this.setData({
            showTransfer: true,
            transferForm
        })
    },
    /** 取消转交 */
	closeTransfer(e){
		this.setData({
			showTransfer: false
		})
	},
	/** 确认转交 */
	confirmTransfer(e){
        // 传入表单数据，调用验证方法
        if (!this.WxValidate.checkForm(this.data.transferForm)) {
            const error = this.WxValidate.errorList[0]
            this.showModal(error)
            return false
        }
        request({
            url: `/merchantMarketing/addMerchantTransferInfo`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: false, // 返回值是否解密
            data: this.data.transferForm
        }).then(res => {
            if(res.code == 0){
                wx.showToast({
                    title: '转交成功',
                    icon: 'none',
                    mask: true,
                    duration: 2000
                });
                this.setData({
                    showTransfer: false
                })
                setTimeout(()=>{
                    this.resetScroller()
                    this.getMyPersonList();
                },2000)
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 表单验证
    initValidate() {
        // 验证字段的规则
        const rules = {
            recipientDeptId: {
                required: true
            },
            recipientId: {
                required: true
            }
        }
        // 验证字段的提示信息，若不传则调用默认的信息
        const messages = {
            recipientDeptId: {
                required: '请选择转交机构',
            },
            recipientId: {
                required: '请选择转交客户经理'
            }
        }

        // 创建实例对象
        this.WxValidate = new WxValidate(rules, messages)
    },
    showModal(error) {
        wx.showToast({
            title: error.msg,
            icon: 'none',
            duration: 2000
        })
    },
    
    /** 删除个人 */
    deletePreson(e){
        let { item } = e.currentTarget.dataset;
        let that = this;
        // 当参数值为0时，允许员工删除；当参数值为1时，则删除时提醒“请联系管理员删除该企业信息”。
        if(this.data.isDelete == 0){
            wx.showModal({
                title: '提示',
                content: `是否删除该个人？`,
                success (res) {
                    if (res.confirm) {
                        if(that.data.isDeleteProcess == 1){
                            request({
                                url: `/businessFlow/addApprovalProcess`,
                                // method: "GET",
                                reqRSAENCRY: true, // 参数是否加密
                                resRSADECRY: true, // 返回值是否解密
                                data: {
                                    flowType: "card_del",
                                    busiId: item.id,
                                    // busiType  1-商户信息，2-企业信息，3-企业楼宇（厂区），4-个人信息，5-个人网格，6.-农业主体信息
                                    busiType: 4,
                                    keyInfo: {
                                        cname: item.perCustName,
                                        busiId: item.id,
                                        busiType: 4,
                                    }
                                }
                            }).then(res => {
                                if(res.code == 0){
                                    wx.navigateTo({
                                        url: '/manager/pages/todotask/index',
                                    })
                                }
                            }).catch(error => {
                                // console.log(error)
                            })
                        }else{
                            request({
                                url: `/personMarketing/changePersonStatus`,
                                // method: "GET",
                                reqRSAENCRY: true, // 参数是否加密
                                resRSADECRY: false, // 返回值是否解密
                                data: {
                                    id: item.id
                                }
                            }).then(res => {
                                if(res.code == 0){
                                    if(res.code == 0){
                                        wx.showToast({
                                            title: '删除成功',
                                            icon: 'none',
                                            mask: true,
                                            duration: 2000
                                        });
                                        setTimeout(()=>{
                                            that.resetScroller()
                                            that.getMyPersonList();
                                        },2000)
                                    }
                                }
                            }).catch(error => {
                                // console.log(error)
                            })
                        }
                        // console.log('用户点击确定')
                    } else if (res.cancel) {
                        // console.log('用户点击取消')
                    }
                }
            })
        }else{
            wx.showToast({
                title: '请联系管理员删除该个人信息',
                icon: 'none',
                duration: 2000
            });
        }
    },
    /**
     * 跳转拜访记录
     */
    toVisit(e) {
        let { id, type } = e.currentTarget.dataset;
        wx.navigateTo({
          url: `/manager/pages/visit/index?merchantId=${id}&merchantType=${type}`,
        })
    },
    /**
     * 跳转添加
     */
    toAddPerson(e) {
        request({
            url: `/personMarketing/verifyAreaAddPer`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: false, // 返回值是否解密
            data: {
                areaId: this.data.perAreaId
            }
        }).then(res => {
            console.log(res)
            if(res.code == 0){
                wx.navigateTo({
                    url: `/manager/pages/addpersonstep/index`,
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
})